import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { categoriesAPI, medicinesAPI } from "./services/products";
import { useDispatch } from "react-redux";
import { delitasadd } from "../store/feature/detials";

function Drug() {
  const [list, uselist] = useState([]);
  const [id, useId] = useState("");
  const [page, usePage] = useState("1");
  const [keyword, useKeyword] = useState("");
  const [medicines, useMedicines] = useState([]);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  useEffect(() => {
    categoriesAPI().then((res) => {
      console.log(res.data);

      uselist(res.data);
    });
  }, []);
  useEffect(() => {
    medicinesAPI({
      category: id,
      per: "10",
      page: page,
      keyword: keyword,
    }).then((res) => {
      useMedicines(res.data.list);
    });
  }, [id, keyword]);
  return (
    <div>
      <div style={{ padding: "0.5rem,0" }}>
        <input
          type="text"
          placeholder="请输入药品关键词"
          style={{ width: "100%", height: "2rem" }}
          onKeyUp={(e) => {
            if (e.keyCode == 13 && e.currentTarget.value) {
              useKeyword(e.currentTarget.value);
              e.currentTarget.value = "";
            }
          }}
        />
      </div>
      <div style={{ display: "flex", justifyContent: "space-around" }}>
        <div style={{ display: "flex", flexDirection: "column", width: "18%" }}>
          {list.map((item: any) => (
            <button
              key={item.id}
              style={{ margin: "0.2rem" }}
              onClick={() => {
                useId(item.id);
              }}
            >
              {item.name}
            </button>
          ))}
        </div>
        <div style={{ display: "flex", flexDirection: "column", width: "75%" }}>
          {medicines.map((item: any) => (
            <div
              key={item.id}
              style={{ display: "flex", flexDirection: "column" }}
            >
              <span>{item.name}</span>
              <span>价格：{item.price}￥</span>
              <img
                src={item.image}
                alt="图片"
                onClick={() => {
                  /*                 dispatch(delitasadd(item.id)); */
                  navigate("/delitas", { replace: false, state: item.id });
                }}
              />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export default Drug;
